﻿import sys  
import cv2  
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog  
from PyQt5.QtGui import QPixmap, QImage 
from PyQt5.QtCore import Qt, pyqtSlot  
  
class ImageTranslationApp(QWidget):  
    def __init__(self):  
        super().__init__()  
  
        self.initUI()  
  
    def initUI(self):  
        # 设置窗口标题和大小  
        self.setWindowTitle('Image Translation with OpenCV and PyQt5')  
        self.setGeometry(300, 300, 600, 500)  
  
        # 创建布局  
        layout = QVBoxLayout()  
  
        # 创建按钮并添加到布局中  
        self.translate_button = QPushButton('Translate Image', self)  
        self.translate_button.clicked.connect(self.translate_image)  
        layout.addWidget(self.translate_button)  
  
        # 创建标签来显示图像  
        self.image_label = QLabel(self)  
        layout.addWidget(self.image_label)  
  
        # 设置窗口布局  
        self.setLayout(layout)  
  
        # 加载图像  
        self.load_image()  
  
    def load_image(self):  
        # 打开文件对话框选择图像文件  
        options = QFileDialog.Options()  
        options |= QFileDialog.DontUseNativeDialog  
        fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",  
                                                    "All Files (*);;JPEG Files (*.jpeg);;PNG Files (*.png)", options=options)  
        if fileName:  
            # 使用OpenCV读取图像，并转换为QImage以在QLabel中显示  
            self.image = cv2.imread(fileName)  
            self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)  
            h, w, ch = self.image.shape  
            bytesPerLine = ch * w  
            convertToQtFormat = QImage(self.image.data, w, h, bytesPerLine, QImage.Format_RGB888)  
            self.pixmap = QPixmap.fromImage(convertToQtFormat)  
            self.image_label.setPixmap(self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio))  
  
    @pyqtSlot()  
    def translate_image(self):  
        # 在这里实现图像平移逻辑  
        # 例如，将图像向右移动10个像素，向下移动20个像素  
        tx, ty = 10, 20  
        M = np.float32([[1, 0, tx], [0, 1, ty]])  
        translated_image = cv2.warpAffine(self.image, M, (self.image.shape[1], self.image.shape[0]))  
  
        # 更新QLabel以显示平移后的图像  
        translated_image = cv2.cvtColor(translated_image, cv2.COLOR_BGR2RGB)  
        h, w, ch = translated_image.shape  
        bytesPerLine = ch * w  
        convertToQtFormat = QImage(translated_image.data, w, h, bytesPerLine, QImage.Format_RGB888)  
        self.pixmap = QPixmap.fromImage(convertToQtFormat)  
        self.image_label.setPixmap(self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio))  
  
if __name__ == '__main__':  
    app = QApplication(sys.argv)  
    ex = ImageTranslationApp()  
    ex.show()  
    sys.exit(app.exec_())